package api

import (
	"github.com/gin-gonic/gin"
	"go-gin-example/pkg/app"
	"go-gin-example/pkg/e"
	"go-gin-example/pkg/upload"
	"go.uber.org/zap"
	"net/http"
)

// UploadImage
// @tags  图片管理
// @Summary 图片上传
// @Produce json
// @Param image formData file true "upload file"
// @Success 200 {string} json "{"code":200,"data":{},"msg":"ok"}"
// @Router /upload [post]
func UploadImage(c *gin.Context) {
	appG := app.Gin{C: c}
	file, image, err := c.Request.FormFile("image")
	if err != nil {
		zap.L().Error("", zap.Error(err))
		appG.Response(http.StatusInternalServerError, e.ERROR, nil)
		return
	}
	if image == nil {
		appG.Response(http.StatusBadRequest, e.InvalidParams, nil)
		return
	}

	imageName := upload.GetImageName(image.Filename)
	fullPath := upload.GetImageFullPath()
	savePath := upload.GetImagePath()
	src := fullPath + imageName
	if !upload.CheckImageExt(imageName) || !upload.CheckImageSize(file) {
		appG.Response(http.StatusBadRequest, e.ErrorUploadCheckImageFormat, nil)
		return
	}

	if err = upload.CheckImage(fullPath); err != nil {
		zap.L().Error("", zap.Error(err))
		appG.Response(http.StatusInternalServerError, e.ErrorUploadCheckImageFail, nil)
		return
	}

	if err := c.SaveUploadedFile(image, src); err != nil {
		zap.L().Error("", zap.Error(err))
		appG.Response(http.StatusInternalServerError, e.ErrorUploadSaveImageFail, nil)
		return
	}

	data := make(map[string]string)
	data["image_url"] = upload.GetImageFullUrl(imageName)
	data["image_save_url"] = savePath + imageName
	appG.Response(http.StatusOK, e.SUCCESS, data)
}
